package com.lovo.frame;

import com.lovo.pojo.UserDO;
import com.lovo.service.UserService;
import com.lovo.service.impl.UserServiceImpl;
import com.lovo.util.Util;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * 登录界面
 */
public class LoginPanel extends JPanel implements ActionListener {
    private ATM frame;
    private JLabel accountLabel = new JLabel("账号：");
    private JLabel pwdLabel = new JLabel("密码：");
    private JTextField accountTextField = new JTextField();
    private JPasswordField pwdField = new JPasswordField();
    private JButton loginBtn = new JButton(Util.getIcon("/images/buttonLand.jpg"));
    private JButton registerBtn = new JButton(Util.getIcon("/images/buttonLogin.jpg"));
    private Font font = new Font("宋体", Font.BOLD, 25);
    //创建一个服务层对象
    private UserService userService = new UserServiceImpl();
    // 错误次数
    private int errorCount = 3;

    public LoginPanel(ATM frame) {
        this.frame = frame;
        this.setLayout(null);
        accountLabel.setBounds(300, 200, 80, 50);
        accountLabel.setFont(font);
        accountTextField.setBounds(380, 200, 250, 50);
        accountTextField.setFont(font);
        pwdLabel.setBounds(300, 250, 80, 50);
        pwdLabel.setFont(font);
        pwdField.setBounds(380, 250, 250, 50);
        pwdField.setFont(font);
        loginBtn.setBounds(420, 320, 140, 50);
        loginBtn.addActionListener(this);

        registerBtn.setBounds(420, 400, 140, 50);//设置注册按钮
        registerBtn.addActionListener(this);//加入监听

        this.add(accountLabel);
        this.add(accountTextField);
        this.add(pwdLabel);
        this.add(pwdField);
        this.add(loginBtn);
        this.add(registerBtn);//加入注册按钮

        this.setOpaque(false);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == loginBtn) {
            //获取输入框内容
            String username = accountTextField.getText();
            String pwd = String.valueOf(pwdField.getPassword());
            //通过服务层方法获取用户
            UserDO user = userService.getByUsernameAndPwd(username,pwd);
            if (user!=null){
                frame.setLoginUser(user);
                frame.switchPanel("menu");
                return;
            }
            errorCount--;
            if (errorCount == 0) {
                JOptionPane.showMessageDialog(this, "次数用完，卡被吞掉");
                System.exit(0);
            }
            JOptionPane.showMessageDialog(this, "登录失败，还剩" + (errorCount) + "次");


        } else if (e.getSource() == registerBtn) {
            frame.switchPanel("register");
        }

    }
}
